package com.luhui.commons.beans;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with LXD
 *
 * @author:Luhui
 * @qq:729913162
 * @Date:2018-08-06
 * @Time:14:39
 */
public class GetSetMethodCache {

    private final Map<Class<?>,Map<String,Method>> SET_METHOD_CACHE = new ConcurrentHashMap<>();
    private final Map<Class<?>,Map<String,Method>> GET_METHOD_CACHE = new ConcurrentHashMap<>();

    public Method getGetMethod(Class<?> clazz,String fieldName) throws IntrospectionException {
        Map<String, Method> classMap = GET_METHOD_CACHE.get(clazz);
        if(classMap == null){
            classMap = new ConcurrentHashMap<>();
            GET_METHOD_CACHE.put(clazz,classMap);
        }

        Method method = classMap.get(fieldName);
        if(method == null){
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName,clazz);
            method = propertyDescriptor.getReadMethod();
            classMap.put(fieldName,method);
        }
        return method;
    }


    public Method getSetMethod(Class<?> clazz,String fieldName) throws IntrospectionException {
        Map<String, Method> classMap = SET_METHOD_CACHE.get(clazz);
        if(classMap == null){
            classMap = new ConcurrentHashMap<>();
            SET_METHOD_CACHE.put(clazz,classMap);
        }

        Method method = classMap.get(fieldName);
        if(method == null){
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName,clazz);
            method = propertyDescriptor.getWriteMethod();
            classMap.put(fieldName,method);
        }
        return method;
    }


}
